import React, { useState } from 'react';
import './LoginModal.css';

interface LoginModalProps {
  visible: boolean;
  onClose: () => void;
  onLoginSuccess?: (token: string) => void;
}

const LoginModal: React.FC<LoginModalProps> = ({ visible, onClose, onLoginSuccess }) => {
  const [phone, setPhone] = useState('');
  const [code, setCode] = useState('');
  const [sending, setSending] = useState(false);
  const [countdown, setCountdown] = useState(0);

  // 模拟发送验证码
  const sendCode = () => {
    if (!/^1\d{10}$/.test(phone)) {
      alert('请输入正确的手机号');
      return;
    }
    setSending(true);
    setCountdown(60);
    // 模拟接口
    setTimeout(() => setSending(false), 1000);
    const timer = setInterval(() => {
      setCountdown((c) => {
        if (c <= 1) {
          clearInterval(timer);
          return 0;
        }
        return c - 1;
      });
    }, 1000);
  };

  // 模拟登录
  const handleLogin = () => {
    if (!/^1\d{10}$/.test(phone)) {
      alert('请输入正确的手机号');
      return;
    }
    if (!/^\d{4,6}$/.test(code)) {
      alert('请输入验证码');
      return;
    }
    // 这里可替换为真实接口
    setTimeout(() => {
      alert('登录成功');
      onLoginSuccess?.('mock-token');
      onClose();
    }, 800);
  };

  if (!visible) return null;

  return (
    <div className="login-modal-mask" onClick={onClose}>
      <div className="login-modal" onClick={e => e.stopPropagation()}>
        <div className="login-title">手机号登录</div>
        <input
          className="login-input"
          type="tel"
          placeholder="请输入手机号"
          value={phone}
          onChange={e => setPhone(e.target.value)}
          maxLength={11}
        />
        <div className="login-code-row">
          <input
            className="login-input"
            type="text"
            placeholder="验证码"
            value={code}
            onChange={e => setCode(e.target.value)}
            maxLength={6}
          />
          <button
            className="code-btn"
            disabled={sending || countdown > 0}
            onClick={sendCode}
          >
            {countdown > 0 ? `${countdown}s后重试` : '获取验证码'}
          </button>
        </div>
        <button className="login-btn" onClick={handleLogin}>登录</button>
        <span className="login-close" onClick={onClose}>×</span>
      </div>
    </div>
  );
};

export default LoginModal;
